// created on 26.07.2007 at 17:20
using System;
using System.Diagnostics;
using Gtk;
using System.Threading;

namespace Designer
{
public class BuildGame : SingletonManager<BuildGame>
{
	public static void Threader()
	{
		while(!BuildGame.Instance.proc.HasExited)
		{
		//Has to parse output
		if(BuildGame.Instance.bar.Fraction == 1)
			continue;
		string line = BuildGame.Instance.proc.StandardOutput.ReadLine();
		if(line.StartsWith("ERROR: "))
		{
			BuildGame.Instance.errormsg = line;
			BuildGame.Instance.dlg.Respond(ResponseType.No);
			return;
		}
		else if(line.StartsWith("Compiling "))
			BuildGame.Instance.bar.Fraction = 0.3;
		else if(line.StartsWith("Cleanup...Done"))
			BuildGame.Instance.bar.Fraction = 1;
		}
		BuildGame.Instance.dlg.Respond(ResponseType.Ok);
	}
	public string builderExe;
	Dialog dlg;
	Process proc;
	ProgressBar bar;
	string errormsg;
	
	public bool Build(string srcfile, string outfile)
	{
		errormsg = "";
		proc = new Process();
		if(System.IO.Path.DirectorySeparatorChar == '\\')
		{
			proc.StartInfo.FileName = builderExe;
			proc.StartInfo.Arguments = "\""+srcfile+"\" \""+outfile+"\"";
		}
		else
		{
			proc.StartInfo.FileName = "mono";
			proc.StartInfo.Arguments = "\""+builderExe+"\" \""+srcfile+"\" \""+outfile+"\"";
		}
		proc.StartInfo.UseShellExecute = false;
		proc.StartInfo.RedirectStandardOutput = true;
		
		proc.Start();
		
		dlg = new Dialog("Kompilieren...",ResourceMgr.Instance.Win, DialogFlags.Modal);
		dlg.DefaultWidth= 200;
		VBox vb = (VBox) dlg.Children[0];
		vb.Add(new Label("Kompiliere Spiel..."));
		bar = new ProgressBar();
		bar.Fraction = 0;
		vb.Add(bar);
		vb.ShowAll();
		//The thread parses the builder output and closes the status dialog if finished
		Thread thread = new System.Threading.Thread(new ThreadStart(Threader));
		thread.Start();
		ResponseType RetVal = (ResponseType)dlg.Run();
		dlg.Destroy();
		
		if(RetVal == ResponseType.No)
		{
			MessageDialog message = new MessageDialog(ResourceMgr.Instance.Win, DialogFlags.Modal, MessageType.Error, ButtonsType.None, false, "");
			message.Text = errormsg;
			message.Title = "Fehler beim Kompilieren";
			message.AddButton(Stock.Ok, ResponseType.Ok);
			message.Run();
			message.Destroy();
			return false;
		}
		else if(RetVal == ResponseType.DeleteEvent)
		{
			if(System.IO.File.Exists(outfile))
				System.IO.File.Delete(outfile);
			return false;
		}
		
		return System.IO.File.Exists(outfile);
	}
	public void RunGame(string file)
	{
		Process proc = new Process();
		if(System.IO.Path.DirectorySeparatorChar == '\\')
		{
			proc.StartInfo.FileName = file;
		}
		else
		{
			proc.StartInfo.FileName = "mono";
			proc.StartInfo.Arguments = "\""+file+"\"";
		}
		proc.Start();
		while(!proc.HasExited) {}
		System.Threading.Thread.Sleep(100);
	}
}
}